package com.ruoyi.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

/**
 * @Package: com.ruoyi.common.utils
 * @Author: HanWL
 * @CreateTime: 2023-10-16 17:29
 * @Version: 1.0
 **/
@Component
public class MailUtils {

    @Resource
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String text){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        sender.send(message);
    }

    public static int calculateAgeFromIDCard(String idCard) throws IllegalArgumentException {
        if (idCard == null || idCard.length() != 18) {
            return -1;
        }

        // 提取出生日期部分
        String birthDateStr = idCard.substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算年龄
        Period period = Period.between(birthDate, currentDate);
        return period.getYears();
    }
}
